$(document).bind('ready ajaxComplete', function() {
	var start, end;
	//add-receipt popup generate current date
	date1 = new Date();
	$(".date-miladi-fixed").val(date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + date1.getDate());
	$('.date_hijri').text(writeIslamicDate(date1, 1));
	$('#date_hijri').val(writeIslamicDate(date1, 1));

	$(function() {
		$("[id^=from-]").each(function() {
			var parts = $(this).attr('id').split('-');
			var no = parts[1];
			$(this).datepicker({
				changeMonth : true,
				numberOfMonths : 1,
				dateFormat : 'yy-mm-dd',
				onClose : function(selectedDate) {
					$("input#to-" + no).datepicker("option", "minDate");
				}
			});
		});

		$("[id^=to-]").each(function() {
			var parts = $(this).attr('id').split('-');
			var no = parts[1];
			$(this).datepicker({
				changeMonth : true,
				numberOfMonths : 1,
				dateFormat : 'yy-mm-dd',
				onClose : function(selectedDate) {
					$("input#from-" + no).datepicker("option", "maxDate", selectedDate, $.datepicker.regional[""]);
				}
			});
		});
		$("#from-miladi").datepicker({
			defaultDate : "+1w",
			changeMonth : true,
			dateFormat : 'yy-mm-dd',
			numberOfMonths : 1,
			onClose : function(selectedDate) {
				$("#to-miladi").datepicker("option", "minDate", selectedDate);
			}
		});

		$("#to-miladi").datepicker({
			defaultDate : "+1w",
			changeMonth : true,
			dateFormat : 'yy-mm-dd',
			numberOfMonths : 1,
			onClose : function(selectedDate) {
				$("#from-miladi").datepicker("option", "maxDate", selectedDate);
			}
		});
		
	});
	//magnificPopup selector for modal false
	$('.ajax-pop-ups-magnific-no-modal').magnificPopup({
		type : 'ajax',
		modal : false,
		showCloseBtn : false,
		closeBtnInside : false,
		callbacks : {
			ajaxContentAdded : function() {
				if ($('.edit-apartment').length) {
					var currentDate = new Date();
					var dd = currentDate.getDate();
					var mm = currentDate.getMonth() + 1;
					var yyyy = currentDate.getFullYear();
					if (dd < 10) {
						dd = '0' + dd
					}
					if (mm < 10) {
						mm = '0' + mm
					}
					var currentDate = yyyy + '-' + mm + '-' + dd;

					var start = $('#from-miladi').val();
					if ((new Date(start).getTime() != new Date(currentDate).getTime())) {
						$('.edit-apartment').hide();
					}
				}
			},
		}
	});

	//magnificPopup selector for modal true
	$('.ajax-pop-up-magnific-modal').magnificPopup({
		type : 'ajax',
		modal : true,
		fixedContentPos : true
	});

	$(".addAppartment").validate({
		rules : {
			name : "required",
			daily_rent : "required",
			monthly_rent : "required",
			heightest_price : "required"
		},

		messages : {
			name : "من فضلك ادخل أسم الوحدة",
			daily_rent : "من فضلك ادخل قيمة الإيجار اليومى",
			monthly_rent : "من فضلك ادخل قيمة الايجار الشهرى",
			heightest_price : "من فضلك أدخل قيمة سعر الذروة"

		}
	});

	// add_furnture validation

	$(".add_furn").validate({
		rules : {
			descrip : "required",
			price : "required",
			source : "required",

		},

		messages : {
			descrip : "تحقق من الوصف",
			price : "تحقق من السعر",
			source : "تحقق من المنشأ",

		}
	});

	$(".add_userM").validate({
		rules : {
			first_name : "required",
			last_name : "required",
			username : "required",
			email : "required",
			phone : "required",
			password : "required",
			confirm_password : "required",
		},

		messages : {
			first_name : "ادخل الاسم الاول",
			last_name : "ادخل الاسم الاخير",
			username : "ادخل اسم المستخدم",
			email : "من فضلك تأكد من ادخال البريد الاليكترونى بطريقه صحيحه",
			phone : "ادخل رقم الجوال",
			password : "ادخل كلمة المرور",
			confirm_password : "ادخل تأكيد كلمة المرور",
		}
	});

	$(".profile").validate({
		rules : {
			first_name : "required",
			last_name : "required",
			username : {
				required : true,
				minlength : 4
			},
			password : {
				required : true,
				minlength : 6
			},
			confirm_password : {
				required : true,
				minlength : 6,
				equalTo : "#password"
			},
			email : "required",
			phone : "required",
		},

		messages : {
			first_name : "ادخل الاسم الاول",
			last_name : "ادخل الاسم الاخير",
			username : "ادخل اسم المستخدم",
			email : "من فضلك تأكد من ادخال البريد الاليكترونى بطريقه صحيحه",
			phone : "ادخل رقم الجوال",
			password : {
				required : "من فضلك أدخل كلمة المرور",
				minlength : "كلمة المرور ينبغى ان تحتوى على 6 أحرف على الاقل"
			},
			confirm_password : {
				required : "من فضلك أدخل تأكيد كلمة المرور",
				minlength : "كلمة المرور ينبغى ان تحتوى على 6 أحرف على الاقل",
				equalTo : "كلمة المرور غير متطابقة"
			},
		}
	});

	//Login form Validation
	$("#sign-up-form").validate({
		rules : {
			name : "required",
			user_password : "required"
		},

		messages : {
			name : "من فضلك أدخل أسم المستخدم",
			user_password : "من فضلك ادخل كلمة المرور"

		}
	});

	//Customer Validation
	$(".validateCustomer").validate({
		rules : {
			name : "required",
			identification_number : "required",
			mobile : "required",
			nationality : "required",
			client_type : "required"
		},

		messages : {
			name : "من فضلك ادخل اسم العميل",
			identification_number : "من فضلك ادخل رقم الإثبات",
			mobile : "من فضلك ادخل الجوال",
			nationality : "من فضلك ادخل جنسية العميل",
			client_type : "من فضلك أدخل نوع العميل"
		}
	});

	//Company Validation
	$("#add-2").validate({
		messages : {
			name : "من فضلك ادخل اسم الشركة",
			mobile : "من فضلك ادخل هاتف الشركة",
			city : "من فضلك ادخل المدينة",
			representative : "من فضلك ادخل الشخص المسئول",
			discount : "من فضلك ادخل الخصم",
			address : "من فضلك ادخل العنوان",
		}
	});

	$(".date_miladi").datepicker({
		changeMonth : true,
		numberOfMonths : 1,
		dateFormat : 'yy-mm-dd',
		onClose : function() {
			var date1 = $(this).datepicker('getDate');
			$(this).parents('form').find('.date_hijri').text(writeIslamicDate(date1, 1));
			$(this).parents('form').find('#date_hijri').val(writeIslamicDate(date1, 1));
		}
	});

	//colorbox selector for nested calls
	$('.ajax-pop-up').colorbox({
		closeButton : true,
		escKey : false,
		onOpen : function() {
			//close opened magnific popup
			magnificPopup = $.magnificPopup.instance;
			//keep its id for later call
			magnificPopupSelector = magnificPopup.contentContainer.children('div').first().attr('id');
			$('#' + magnificPopupSelector).hide();
			$('.mfp-wrap').hide();

		},
		onComplete : function() {
		},
		onClosed : function() {
			$('#' + magnificPopupSelector).show();
			$('.mfp-wrap').show();
		},
	});

});

$(document).bind('ready', function() {

	//open recent contract after redirection if any
	recent_contract = $('.recieveRecentContrat').val();
	if (recent_contract > -1) {
		$.magnificPopup.open({
			items : {
				src : 'edit-pop-ups/contract.php?id=' + recent_contract,
			},
			type : 'ajax',
		});
	}

	$('.send-sms').live("click", function() {
		message = $('#notEncodedMessage').val();
		$('#sms-message').val(message);
		button_object = $(this);
		form = $(this).parents('form')
		$(form).submit();
		$(form).submit(function() {
			if ($(form).valid()) {
				$(button_object).attr("disabled", "disabled");
				$(button_object).addClass("disabled-style");
			}
		});
	});

	//save magnific popup instance to keep passing it for various functions
	var magnificPopupSelector = 0;

	//Change the total price considering service revenue and Discounts
	function changePrice() {
		var company_discount = 0, discount = 0, paid = 0, recently_paid = 0;
		service_reveneue = 0, fixed_discount = 0, price = 0, period = 0, total_discount = 0;
		;

		if ($.isNumeric(parseFloat($('#total_service_revenue').val())))
			service_reveneue = parseFloat($('#total_service_revenue').val());

		if ($('.discount').text() != "") {
			company_discount = parseFloat($('.discount').text());
		}

		if ($.isNumeric($('.get-discount').val())) {
			discount = parseFloat($('.get-discount').val());
		}

		if ($.isNumeric($('.get-fixed-discount').val())) {
			fixed_discount = parseFloat($('.get-fixed-discount').val());
		}

		if ($.isNumeric($('#apartment-price').text())) {
			price = parseFloat($('#apartment-price').text());
		}
		if ($.isNumeric($('.period-days').val()) && $('.rent_type').val() == 0) {
			period = parseInt($('.period-days').val());
		} else if ($.isNumeric($('.period-days').val()) && $('.rent_type').val() == 1) {
			period = parseFloat($('.period-days').val()) / 7;
		} else if ($.isNumeric($('.period-days').val()) && $('.rent_type').val() == 2) {
			period = parseFloat($('.period-days').val()) / 30;
		}

		if ($.isNumeric(parseFloat($('.discountAnight').text()))) {
			maxd = $('.discountAnight').text();
			$('#maxd').val(maxd * period);
		}

		current = price * period;
		$('#final_price').val(current.toFixed(2));
		//total value to be entered into DB without considering services_revenues
		$('.total_price').text((current + service_reveneue).toFixed(2));
		total_discount = discount + company_discount;
		//apply percentage discount
		current = current - ((total_discount));

		//apply fixed discount and check if fixed discount is greater than current
		if (fixed_discount > current) {
			alert("مبلغ الخصم لا يمكن أن يكون أكبر من قيمة الايجار");
			$('.get-fixed-discount').val()
		} else
			current = current - fixed_discount;

		//add service revenue excluding it from discount
		current += service_reveneue;

		//update prices
		$('.final_price').text(current.toFixed(2));
		$('.one_night_price').text((current / period).toFixed(2));

		$('.credit').text(0 - current.toFixed(2));

		paid = parseFloat($('.what_paid').text());
		paid_back = parseFloat($('.paid_back').text());
		credit = $('.final_price').text();
		new_credit = (parseFloat(paid) - parseFloat(paid_back) - parseFloat(credit)  );

		$('.credit').text(new_credit.toFixed(2));

		if (new_credit > 0)
			clas = "green";
		else if (new_credit < 0)
			clas = "red";
		else if (new_credit == 0)
			clas = "black";

		//if apartment is pre-chosen, just enable clients
		if ($('#apartment_id').val() != "") {
			$('.company-selection').removeAttr("disabled");
			$('.client-selection').removeAttr("disabled");
			$('.client_add').removeAttr("disabled");
		}

		$('.credit').removeClass('red green black');
		$('.credit').addClass(clas);

	}

	function checkCredit() {
		credit = $('.credit').text();
		insurance = $('.insurance').text();
		if (credit == 0 && insurance == 0) {
			button = $('#what-button').val(3);
			contract_id = $('.contract_id').val();
			$('.sendRecentContrat').val(contract_id);
			$(button).parents('form').submit();
		} else if (credit > 0) {
			var didConfirm = confirm("للعميل مبلغ مستحق لإكمال تصفية العقد، هل تود إنشاء سند صرف بقيمة " + credit + "  ريال سعودى؟  ");
			if (didConfirm == true) {
				contract_id = $('.contract_id').val();
				saveDetailsOnAjax();
				$.magnificPopup.open({
					items : {
						src : 'create-pop-ups/payment.php?id=' + contract_id + "&amount=" + Math.abs(credit),
					},
					type : 'ajax',
				});
			} else {
				//do nothing
			}
		} else if (credit < 0) {
			var didConfirm = confirm("لم يتم تحصيل المبلغ المطلوب لإكمال التكلفة النهائية، هل تود إنشاء سند قبض بالمبلغ المتبقى " + Math.abs(credit) + " ريال سعودى؟");
			if (didConfirm == true) {
				contract_id = $('.contract_id').val();
				saveDetailsOnAjax();
				$.magnificPopup.open({
					items : {
						src : 'create-pop-ups/reciept.php?id=' + contract_id + "&amount=" + Math.abs(credit),
					},
					type : 'ajax',
				});

			} else {
				//do nothing
			}
		} else if (insurance > 0) {
			var didConfirm = confirm("هناك مبلغ للتأمين لم يتم دفعه، هل تود إنشاء سند صرف بالمبلغ؟");
			if (didConfirm == true) {
				credit = parseFloat($('.insurance').text());
				contract_id = $('.contract_id').val();
				saveDetailsOnAjax();
				$.magnificPopup.open({
					items : {
						src : 'create-pop-ups/payment.php?id=' + contract_id + "&amount=" + Math.abs(credit) + "&type=1",
					},
					type : 'ajax',
				});
				return;
			} else {
				return;
			}
		}

	}

	//function to print HTML content such as pop-ups..etc
	function Popup(data) {
		var mywindow = window.open('', 'my div', 'height=400,width=600');
		mywindow.document.write('<html><head><title>عــقــد ايــجــار</title>');
		mywindow.document.write('<link rel="stylesheet" href="css/style.css" type="text/css" />');
		mywindow.document.write('</head><body class="print-stuff" >');
		mywindow.document.write(data);
		mywindow.document.write('</body></html>');

		//return true;
	}

	function PrintElem(elem) {
		Popup($(elem).html());
	}


	$('.print').live("click", function() {
		PrintElem($(this).siblings('.print-wrap'));
	});

	$('.company-select').live("change", function() {
		if ($('.company-select').is(':checked')) {
			$('#getCompanies').submit();
		} else {
			window.location = "customers.php";
		}
	});

	//disable on select
	$('.rent_type').live("change", function() {
		if ($(this).val() == 0) {
			var price = $('#daily_price').val();
			$('#apartment-price').text(price);
			$('#apartment-price-2').text(price);
			changePrice();
		} else if ($(this).val() == 1) {
			var price = $('#weekly_price').val();
			$('#apartment-price').text(price);
			$('#apartment-price-2').text(price);
			changePrice();
		} else {
			var price = $('#monthly_price').val();
			$('#apartment-price-2').text(price);
			$('#apartment-price').text(price);
			changePrice();
		}
	});

	//Increment date by days
	$('.period-days').live("focusout", function() {
		valu = parseInt($(this).val());
		if (isNaN(valu)) {
			valu = 0;
			$('.period-days').val(0);
		}

		if ($("#from-miladi").val() == "") {
			var date = new Date();
			$('#from-miladi').datepicker('setDate', date);
		}

		$('.period-months').val(Math.floor(valu / 30));

		var date1 = $('#from-miladi').datepicker('getDate');
		var date = new Date(Date.parse(date1));
		date.setDate(date.getDate() + valu);

		var newDate = date.toDateString();
		newDate = new Date(Date.parse(newDate));

		$('#to-miladi').datepicker('setDate', date);

		//change by others part
		var date1 = $('#from-miladi').datepicker('getDate');
		$('.show-from-hijri-from').text(writeIslamicDate(date1, 1));
		$('#show-from-hijri-from').val(writeIslamicDate(date1, 1));

		var date1 = $('#to-miladi').datepicker('getDate');
		$('.show-from-hijri-to').text(writeIslamicDate(date1, 1));
		$('#show-from-hijri-to').val(writeIslamicDate(date1, 1));
		//check if apartment is pre-chosen, then I'll have to activate customers part

		$('.apartment-row').removeAttr("disabled");
		changePrice();
	});

	//Increment date by months
	$('.period-months').live("focusout", function() {
		valu = parseInt($(this).val());
		if ($("#from-miladi").val() == "") {
			$('#from-miladi').datepicker('setDate', new Date());
		}

		$('.period-days').val(Math.floor(valu * 30));

		var date1 = $('#from-miladi').datepicker('getDate');
		var date = new Date(Date.parse(date1));
		date.setMonth(date.getMonth() + valu);
		var newDate = date.toDateString();
		newDate = new Date(Date.parse(newDate));

		$('#to-miladi').datepicker('setDate', date);

		//change by others part
		var date1 = $('#from-miladi').datepicker('getDate');
		$('.show-from-hijri-from').text(writeIslamicDate(date1, 1));
		$('#show-from-hijri-from').val(writeIslamicDate(date1, 1));

		var date1 = $('#to-miladi').datepicker('getDate');
		$('.show-from-hijri-to').text(writeIslamicDate(date1, 1));
		$('#show-from-hijri-to').val(writeIslamicDate(date1, 1));

		//check if apartment is pre-chosen, then I'll have to activate customers part
		if ($('#apartment_id').val() != "") {
			$('.company-selection').removeAttr("disabled");
			$('.client-selection').removeAttr("disabled");
			$('.client_add').removeAttr("disabled");
		}

		$('.apartment-row').removeAttr("disabled");
		changePrice();
	});

	//fill hijri on miladi input-change
	$('#from-miladi').live("change", function() {
		var start = $('#from-miladi').datepicker('getDate');
		$('.show-from-hijri-from').text(writeIslamicDate(start, 1));
		$('#show-from-hijri-from').val(writeIslamicDate(start, 1));
		end = $('#to-miladi').datepicker('getDate');
		if (end != null) {
			var days = (end - start) / 1000 / 60 / 60 / 24;
			var months = Math.floor(days / 30);

			if (end - start == 0)
				$('.period-days').val(1);
			else
				$('.period-days').val(parseInt(days));

			$('.period-months').val(months);
			changePrice();
			$('.apartment-row').removeAttr("disabled");
		}

		//change the edit icon state checking wheather start today is today or not
		if ($('.edit-apartment').length) {
			var currentDate = new Date();
			var dd = currentDate.getDate();
			var mm = currentDate.getMonth() + 1;
			var yyyy = currentDate.getFullYear();
			if (dd < 10) {
				dd = '0' + dd
			}
			if (mm < 10) {
				mm = '0' + mm
			}
			var currentDate = yyyy + '-' + mm + '-' + dd;
			var start = $('#from-miladi').val();
			if ((new Date(start).getTime() < new Date(currentDate).getTime())) {
				$('.edit-apartment').hide();
			} else
				$('.edit-apartment').show();
		}

	});

	//fill hijri on miladi input-change
	$('#to-miladi').live("change", function() {
		var end = $('#to-miladi').datepicker('getDate');
		$(this).parents('.add_bookings').find('.show-from-hijri-to').text(writeIslamicDate(end, 1));
		$(this).parents('.add_bookings').find('#show-from-hijri-to').val(writeIslamicDate(end, 1));
		start = $('#from-miladi').datepicker('getDate');
		if (start != null) {
			var days = (end - start) / 1000 / 60 / 60 / 24;
			if (days < 0)
				days = 0;

			var months = Math.floor(days / 30);

			if ((end - start) == 0)
				$('.period-days').val(1);
			else
				$('.period-days').val(parseInt(days));

			$('.period-months').val(months);
			changePrice();
			$('.apartment-row').removeAttr("disabled");
		}
	});

	page = $('.currentPage').text();
	elements = $('.totalPages').text();
	total = Math.ceil(elements / 20);

	//for searchresults page
	$('#page-selection,#apartments-selection,#contracts-selection,#fur-selection,#payment-selection,#recipt-selection ,#units_reports , #monthly_report-selection ,#employee-selection ,#requests-selection,#traffic-selection').bootpag({
		total : total,
		leaps : false,
		next : "التالى",
		prev : "السابق",
		page : page,
		maxVisible : 10,
	}).on('page', function(event, num) {
		if ($('#page-selection').length)
			window.location = "customers.php?page=" + num;

		if ($('#apartments-selection').length) {
			var data = $('#searchClient').serialize();
			window.location = "apartments.php?" + data + "&page=" + num;

		}

		if ($('#contracts-selection').length) {

			$('#page').val(num);
			$('#searchClient').submit();

		}

		if ($('#fur-selection').length) {
			var apart = $('.fur_filter :selected').val();
			window.location = "furnitures.php?page=" + num + "&apart=" + apart;
		}

		if ($('#payment-selection').length) {
			$('#page').val(num);
			$('#searchClient').submit();
		}
		if ($('#recipt-selection').length) {
			$('#page').val(num);
			$('#searchClient').submit();
		}
		if ($('#units_reports').length) {
			$('#page').val(num);
			$('#searchClient').submit();
		}
		if ($('#monthly_report-selection').length) {
			$('#page').val(num);
			$('#searchClient').submit();
		}
		if ($('#employee-selection').length) {
			$('#page').val(num);
			$('#searchClient').submit();
		}
		if ($('#requests-selection').length) {
			$('#page').val(num);
			$('#searchClient').submit();
		}

		if ($('#traffic-selection').length) {
			$('#page').val(num);
			$('#searchClient').submit();
		}
	});

	$('.fur_filter').live("change", function() {
		var apart = $('.fur_filter :selected').val();
		window.location = "furnitures.php?apart=" + apart;
	});

	//check if session message is visible, then remove it after 5 seconds
	if ($('.success-message-edit,.error-message').is(':visible')) {
		$('.success-message-edit,.error-message').delay(1600);
		$('.success-message-edit,.error-message').fadeOut(500);
	}

	$('#edit_client').ready(function() {
		if ($('.success-message-edit,.error-message').is(':visible')) {
			$('.success-message-edit,.error-message').delay(1600);
			$('.success-message-edit,.error-message').fadeOut(500);
		}
	});

	//delete clients/apartments...etc By Sending Ajax request with a filter to delete.php
	$(".delete").live("click", function() {
		var didConfirm = confirm("هل أنت متأكد من الحذف؟");

		if (didConfirm == true) {
			//$('.loading').show();
			var currentObject = $(this);
			var id = $(currentObject).siblings('.delete-id').val();
			var other = $(currentObject).siblings('.other-id').val();
			var filter = $(currentObject).siblings('.filter-id').val();
			var rtype = $(currentObject).siblings('.rtype').val();
			if (filter == 12) {
				if (rtype <= 1) {
					var didConfirm2 = confirm("حذف هذا المستخدم سيؤدي الي حذف جميع البيانات العقود والوحدات والبيانات المتعلقة به هل انت متأكد من الحذف ؟");
					if (didConfirm2 == true) {
						window.location = "delete.php?other=" + other + "&filter=" + filter + "&id=" + id + "&rtype=" + rtype;
					}
				} else {
					window.location = "delete.php?other=" + other + "&filter=" + filter + "&id=" + id + "&rtype=" + rtype;
				}
			} else {
				window.location = "delete.php?other=" + other + "&filter=" + filter + "&id=" + id;
			}
		} else {
			//do nothing
		}

	});

	//disable unit
	$(".disable").live("click", function() {
		var didConfirm = confirm("هل انت متأكد من تحويل حالة الوحدة إلى غير مفعلة؟");
		if (didConfirm == true) {

			//$('.loading').show();
			var currentObject = $(this);
			var id = $(currentObject).siblings('.disable-id').val();
			var page = $(currentObject).siblings('.pages').val();
			var other = $(currentObject).siblings('.other-id').val();
			var filter = $(currentObject).siblings('.disable').val();
			window.location="disable.php?disable="+filter+"&pages="+page+"&id="+id;
		} else {
			//do nothing
		}

	});

	$('.ajax-pop-up').colorbox({
		closeButton : true,
		escKey : false,

	});

	//change event of choosing client SMS
	$('.radio-container :radio,.search-clients-sms').live("change click", function() {
		data = $(this).parents('form').serialize();
		$.ajax({
			type : "GET",
			url : "choose-pop-ups/choose_clients_sms.php",
			dataType : "json",
			data : data,
			success : function(response) {

				$('.customer-table-list .cell-parent').remove();
				if (response == 0) {
					$('.customer-table-list tbody').append('<tr class="cell-parent"><td colspan="3">لا توجد نتائج </td></tr>');
				} else {
					$.each(response, function(index, element) {
						$('.customer-table-list tbody').append('<tr class="cell-parent">' + '<td id="client-name">' + element.name + '</td>' + '<td class="mobile" >' + element.mobile + '</td>' + '<td ><input type="checkbox" name="selectClient" class="get_value_CB" value=" ' + element.id + '"/></td></tr>');
					});
				}
				$("td#smsAddClientMessage").text("نتائج البحث");
			}
		});

	});

	//choose apartments and effect its fields on click
	$('.save_chosen_apartments').live("click", function() {
		var total = $('input:checked.chosen-apartments').length;
		var chosen_apartments = "";
		var daily_price = 0;
		var weekly_price = 0;
		var monthly_price = 0;
		var name = "";
		var maxd = 0;
		var apartmentsCounter = 0;
		$('input:checked.chosen-apartments').each(function(index, element) {
			daily_price += parseFloat($(this).parent().siblings('#daily-rent').text());
			weekly_price += parseFloat($(this).parent().siblings('#weekly-rent').text());
			monthly_price += parseFloat($(this).parent().siblings('#monthly-rent').text());
			maxd += parseFloat($(this).parent().siblings('#maxd').text());
			apartmentsCounter++;

			if (index === total - 1) {
				//ignore pipeline
				chosen_apartments += $(this).attr("apartment_id");
				name += $(this).parent().siblings('#apartment_name').text();
			} else {
				chosen_apartments += $(this).attr("apartment_id") + '|';
				name += $(this).parent().siblings('#apartment_name').text() + ',';
			}

		});
		$.colorbox.close();
		//show recently closed popup
		$('#' + magnificPopupSelector).show();
		$('.mfp-wrap').show();

		if ($('.save_chosen_apartments').attr("id") == 'came_from_companies') {
			$('.apartment-names').text(name);
		} else {
			$('#apartment-found').text(name);
		}
		$('#apartment_names').val(name);
		$('#apartment_id').val(chosen_apartments);
		$('#weekly_price').val(weekly_price);
		$('#daily_price').val(daily_price);
		$('#monthly_price').val(monthly_price);
		$('#maxd').val(parseFloat(maxd));
		$('.max-discount-text .red').text(parseFloat(maxd));

		if ($('.rent_type').val() == 0) {
			var price = daily_price;
		} else if ($('.rent_type').val() == 1) {
			var price = weekly_price;
		} else {
			var price = monthly_price;
		}

		$('#apartment-price').text(price);
		$('#apartment-price-2').text(price);
		$('.company-selection').removeAttr("disabled");
		$('.client-selection').removeAttr("disabled");
		$('.client_addd').removeAttr("disabled");
		changePrice();

	});

	//validate time
	$.validator.addMethod("time", function(value, element) {
		return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
	}, "من فضلك أدخل الوقت بصورة صحيحة");

	$("#editContract").validate({
		rules : {
			time_in : "required time",
			time_out : "required time",
		},

	});

	$('.selectall').live("click", function() {
		if (this.checked) {
			// Iterate each checkbox and change each one of them to checked
			$(':checkbox').each(function() {
				this.checked = true;
			});
		} else {
			// Iterate each checkbox and change it to false
			$(':checkbox').each(function() {
				this.checked = false;
			});
		}
	});

	$('.save-chosen-clients').live("click", function() {
		//keep track of last index
		var total = $('input:checked.get_value_CB').length;
		var mobile_cs = "";
		var name_mob = "";
		$('input:checked.get_value_CB').each(function(index, element) {
			if (this.checked) {
				mobile = $(this).parent().siblings('.mobile').text();
				name = $(this).parent().siblings('#client-name').text();
				if (index == (total - 1)) {
					//ignore comma
					mobile_cs += mobile;
					name_mob += name + ',' + mobile;
				} else {

					mobile_cs += mobile + ',';
					name_mob += name + ',' + mobile + ";\n ";
				}

			}
		});
		$.colorbox.close();
		$('#clients_number').val(name_mob);
		$('.mobiles-cs').val(mobile_cs);
	});

	//choose client and effect its fields on click
	$('.chosen-client').live("click", function() {
		var id = parseInt($(this).attr("id"));
		var name = $(this).parent().parent().find('#client-name').text();
		$('#client_id').val(id);
		$.colorbox.close();

		//show recently closed popup
		$('#' + magnificPopupSelector).show();
		$('.mfp-wrap').show();

		$('.client-found').attr("id", id);
		$('.client-found').text(name);
		$('.discount-control').removeAttr('disabled');
		$('.save-botton,.save-botton2').removeAttr('disabled');
		$('.check-in').removeAttr('disabled');
	});

	//choose client through coompanies plan and effect its fields on click
	$('.chosen-client1').live("click", function() {
		var id = parseInt($(this).attr("id"));
		var name = $(this).parent().parent().find('#client-name').text();
		$('#client_id').val(id);
		$.colorbox.close();

		//show recently closed popup
		$('#' + magnificPopupSelector).show();
		$('.mfp-wrap').show();

		$('.client-found-2').attr("id", id);
		$('.client-found-2').text(name);
		$('.discount-control').removeAttr('disabled');
		$('.save-botton,.save-botton2').removeAttr('disabled');
		$('.check-in').removeAttr('disabled');
	});

	//choose company and effect its fields on click
	$('.chosen-company').live("click", function() {
		//get selected company id
		var id = $(this).attr("id");
		//get selected company name
		var name = $(this).parent().parent().find('#company-name').text();

		$.colorbox.close();
		$('#' + magnificPopupSelector).show();
		$('.mfp-wrap').show();

		//set both name and id in hidden values
		$('#company_id').val(id);
		$('#company_name').val(name);

		//get company discount
		var discount = parseInt($(this).parent().parent().find('#discount').text());

		//set both name and id in text values
		$('.company-found').attr("id", id);
		$('.company-found').text(name);
		//show discount besides company name
		$('.discount').text(discount);
		$('.discount').text(discount);
		changePrice();
	});

	//chosen company thorugh company periods choice
	$('.chosen-company1').live("click", function() {
		//get selected company id
		var id = $(this).attr("id");
		//get selected company name
		var name = $(this).parent().parent().find('#company-name').text();
		$.ajax({
			url : "choose-pop-ups/choose_apartment_via_company.php?id=" + id,
			type : "POST",
			dataType : "html",
			success : function(response) {
				$('.customers-table').remove();
				$('#cboxLoadedContent').append(response);
				$.colorbox.resize();
			}
		});

		//set both name and id in hidden values
		$('#company_id').val(id);
		$('#company_name').val(name);

		//set both name and id in text values
		$('.company-found-2').attr("id", id);
		$('.company-found-2').text(name);

		//show discount besides company name
	});

	$('.delete-company').live("click", function() {
		$('#company_id').val("");
		$('#company_name').val("");
		$('.company-found').text("...");
		$('.discount').text("");
		changePrice();
	});

	$('.get-discount').live("focusout", function() {
		changePrice(); //make rthe required intialization
		max_discount = parseFloat($('#maxd').val());
		given_discount = parseFloat($('.get-discount').val());
		if (given_discount > max_discount) {
			alert("الخصم الذى أدخلته تجاوز القيمة المعطاه لأقصى خصم متاح");
			$('.get-discount').val(max_discount);
		}
		changePrice();
	});

	$('.get-fixed-discount').live("focusout", function() {
		changePrice();
	});

	$('.add-pop,.add_client_pop,.view_client_pop,.edit_client_pop,.add_furnitures_pop,.view_furnitures_pop,.edit_furnitures_pop,.link_vouchers_pop,.sms_send_pop,.sms_send_all_pop,.apartments_type').magnificPopup({
		type : 'inline',

		fixedContentPos : false,
		fixedBgPos : true,

		overflowY : 'auto',

		closeBtnInside : false,
		showCloseBtn : false,
		preloader : false,

		midClick : true,
		removalDelay : 300,
		mainClass : 'my-mfp-zoom-in'

	});

	$('.create-booking-pop-up').magnificPopup({
		type : 'inline',

		fixedContentPos : false,
		fixedBgPos : true,

		overflowY : 'auto',
		showCloseBtn : true,
		modal : true,
		preloader : false,
		midClick : true,
		removalDelay : 300,
		mainClass : 'my-mfp-zoom-in'
	});

	$('.image-filter').live("click", function() {
		$(':input').val('');
		$('select').val('');

		val = $(this).attr('value');
		$('.apartment_status').val(val);
		$('.apartment_filter').submit();
	});

	$('.search-botton').live("click", function() {
		$('#searchClient').submit();
	})

	$('.view_client_pop').live("click", function() {
		date1 = new Date();
		$('.date_hijri').text(writeIslamicDate(date1, 1));
		$('#date_hijri').val(writeIslamicDate(date1, 1));
		var amount = parseFloat($('.final-price').text());
		$('.amout-paid-1').val(amount);
		var service = $('.service_name').val();
		$('#notes').val(service);
	});

	$('.save-botton,.add-button,.edit-button,.add-button-2,.small-botton').live("click", function() {
		form = $(this).parents('form');
		button_object = $(this);
		$(form).submit();
		$(form).submit(function() {
			if ($(form).valid()) {
				$(button_object).attr("disabled", "disabled");
				$(button_object).addClass("disabled-style");
			}
		});
	});

	$('.add-button-no-submit').live("click", function() {
		//if customer add button clicked, check from where the event came from
		if ($(this).parents('#colorbox').length)
			$(this).siblings('.no-submit-related').val(1);
		//check value to submit otherwise send ajax request
		if ($('.no-submit-related').val() == 0) {
			if ($(this).parents('form').valid()) {
				$(this).parents('form').submit();
				$(this).attr("disabled", "disabled");
				$(this).addClass("disabled-style");
			}

		} else {
			if ($(this).parents('form').valid()) {
				var data = $(this).parents('form').serialize();
				var url = $(this).parents('form').attr("action");
				$(this).attr("disabled", "disabled");
				$(this).addClass("disabled-style");

				$.ajax({
					url : url,
					type : "POST",
					data : data,
					dataType : "html",
					success : function(response) {
						if (response == -2)
							alert("رقم اثبات العميل مكرر فى النظام");
						else {
							$.colorbox.close();
							$('#' + magnificPopupSelector).show();

							$('.mfp-wrap').show();
							var obj = response.split(":");
							$('#client_id').val(parseInt(obj[0]));
							if ($('.add-button-no-submit').attr("id") == 1) {
								$('.client-found-2').attr("id", parseInt(obj[0]));
								$('.client-found-2').text(obj[1]);
							} else {
								$('.client-found').attr("id", parseInt(obj[0]));
								$('.client-found').text(obj[1]);
							}

							$('.discount-control').removeAttr('disabled');
							$('.save-botton,.save-botton2').removeAttr('disabled');
							$('.check-in').removeAttr('disabled');
						}
					}
				});
			}

		}
	});

	$('#choose_method').live("change", function() {
		$("input[type^='hidden'][name$='_price']").val("");
		$("input[type^='hidden'][name$='id']").val("");
		$("input[type^='hidden'][name='company_name']").val("");
		$("input#apartment_names,input#final_price").val("");
		$("input[name^='maxd']").val("");
		$(".client-found,.company-found,.company-found-2,.client-found-2,#apartment-found,#apartment-price,#apartment-price-2,.discount,.final_price,.total_price,.final_price,.credit").text("");
		if (this.checked) {
			$('.add_apartment_direct').attr("disabled", "disabled");
			$('.add_apartment_company').removeAttr('disabled');
		} else {
			$('.add_apartment_company').attr("disabled", "disabled");
			$('.add_apartment_direct').removeAttr('disabled');
		}
	});

	$('.save-botton2').live("click", function(e) {
		e.preventDefault();
		form = $(this).parents('form');
		button_object = $(this);
		var data = $("#createContractt").serialize();
		$.ajax({
			type : "POST",
			url : "createContract.php",
			data : data,
			dataType : "html",
			beforeSend : function() {
				$('body').addClass("loading")
			},
			success : function(response) {
				$('body').removeClass("loading");
				var res = response.split("|");

				if (res[0] == -1 || res[0] == -2) {
					$('body').scrollTop(0);
					$('.error-message').show();
					$('.error-message p').text(res[1]);
					$('.save-botton2').removeAttr('disabled');
					$('.success-message-edit,.error-message').delay(1600);
					$('.success-message-edit,.error-message').fadeOut(500);
				} else {
					window.location = "bookings.php";
				}
			}
		});
	});

	//specific for create contract page only
	$('#createContractt .check-in').live("click", function(e) {
		e.preventDefault();
		$(this).attr("disabled", "disabled");
		$(this).addClass("disabled-style");

		date1 = $(this).parents('.bookings-edit-container').find('.check-today').datepicker('getDate');
		date2 = new Date();
		date2.setHours(0, 0, 0, 0);

		if (date1.getTime() <= date2.getTime()) {
			$(this).siblings('#what-button').val(2);
			var data = $("#createContractt").serialize();
			$.ajax({
				type : "POST",
				url : "createContract.php",
				data : data,
				dataType : "html",
				beforeSend : function() {
					$('body').addClass("loading")
				},
				success : function(response) {
					$('body').removeClass("loading");
					var res = response.split("|");

					if (res[0] == -1 || res[0] == -2) {
						$('body').scrollTop(0);
						$('.error-message').show();
						$('.error-message p').text(res[1]);
						$('.check-in').removeAttr('disabled');
						$('.success-message-edit,.error-message').delay(1600);
						$('.success-message-edit,.error-message').fadeOut(500);
					} else {
						window.location = "bookings.php";
					}
				}
			});

		} else {
			alert("يجب ان يكون تاريخ الدخول مساوياً لتاريخ اليوم او اكبر منه حتى يمكن للعميل دخول الوحدة");
		}
	});
	$('#editContract .check-in').live("click", function(e) {
		$(this).attr("disabled", "disabled");
		$(this).addClass("disabled-style");

		date1 = $(this).parents('.bookings-edit-container').find('.check-today').datepicker('getDate');
		date2 = new Date();
		date2.setHours(0, 0, 0, 0);
		if (date1.getTime() <= date2.getTime()) {
			$(this).siblings('#what-button').val(2);
			$(this).parents('form').submit();
		} else {
			alert("يجب ان يكون تاريخ الدخول مساوياً لتاريخ اليوم او اكبر منه حتى يمكن للعميل دخول الوحدة");
		}

	});

	$('#contract_status').live("change", function() {
		$('#searchClient').submit();

	});

	$('.close-button').live("click", function() {
		location.reload();
	});

	$('.close-back').live("click", function() {
		//open recent contract after redirection if any
		//if Fatora
		recent_contract = $('.recieveRecentContrat').val();
		if (recent_contract == -1) {
			//if print receipet
			recent_contract = $('.contract_id').text();
		}
		//if pop-up was opened, open it back
		if ($('#contract_status').val() == 1 && $.isNumeric(recent_contract) && recent_contract != -1) {
			$.magnificPopup.open({
				items : {
					src : 'edit-pop-ups/contract.php?id=' + recent_contract,
				},
				type : 'ajax',
			});
		} else {
			$.magnificPopup.close();
		}
	});

	$('.choose-service').live("click", function() {
		var id = $(this).attr('id');
		window.location = "addService.php?id=" + id;
		$('.selected-service').removeClass('selected-service');
		$(this).addClass('selected-service');
	});

	//getUrlParamters
	$.urlParam = function(name) {
		var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
		if (results == null) {
			return null;
		} else {
			return results[1] || 0;
		}
	}

	$('#add-2,#periods,#submit-message').validate();

	jQuery.extend(jQuery.validator.messages, {
		email : "من فضلك أدخل الايميل بطريقة صحيحة",
		date : "Please enter a valid date.",
	});
	//make sure the % is valid
	function validp(p) {
		if (p >= 0 && p < 100) {
			return true;
		} else {
			return false
		}
	}


	$('.edit-price').editable('apartments-price.php', {
		submitdata : function() {
			pid = $(this).attr("id");
			id = $(this).parent().find('.apart_id').attr("value");
			field = $(this).attr("value");
			return {
				id : id,
				field : field,
				pid : pid
			};
		},
		indicator : 'Saving...',
		tooltip : 'Click to edit...'
	});

	$('.co-edit-price').editable('setcoprice.php', {
		submitdata : function() {
			//Period ID
			pid = $(this).attr("id");
			//Apartment ID
			id = $(this).siblings(".apart_id").attr("value");
			//Daily or Weekly or Monthly
			field = $(this).attr("value");
			//Company ID
			coid = $(this).parent("tr").attr("id");
			return {
				id : id,
				field : field,
				pid : pid,
				cid : coid
			};
		},
		indicator : 'Saving...',
		tooltip : 'Click to edit...'
	});

	$('.edit-md').editable('apartments-price.php', {
		submitdata : function(e) {
			pid = $(this).attr("id");
			id = $(this).parent().find('.apart_id').attr("value");
			v = $(this).children("form").find("input").attr('value');
			if (v < 0) {
				alert("النسبة المدخلة غير صحيحة");
				e.preventDefault();
				return false;
			} else {
				return {
					id : id,
					pid : pid
				};
			}

		},
		indicator : 'Saving...',
		tooltip : 'Click to edit...'
	});

	function changeServicePrice(new_price, arithmtic) {
		var discount = 0;
		var price = parseFloat($('.total-price').text());
		new_price = parseFloat(new_price);

		if (arithmtic == '+')
			price += new_price;
		else
			price -= new_price;

		if ($.isNumeric($('.discount').val()))
			discount = parseFloat($('.discount').val());

		$('.total-price').text(price + " ر.س");

		//apply discount
		price = price - ((discount / 100) * price);
		$('.final-price').text(price + " ر.س");
	}


	$('.edit-quantity').editable(function(data) {
		if ($.isNumeric(data)) {
			$(this).text(data);
			price = $(this).siblings('.price').text();
			total = price * data;
			$(this).siblings('.total').text(total);
			if ($(this).parent().find('.chosen-service').is(':checked'))
				changeServicePrice(total, '+');
		} else {
			alert("please enter a valid number");
		}

	});

	$('.chosen-contract').live("click", function() {
		contract_id = $(this).parents('.cell-parent').find('#contract_id').text();
		client_id = $(this).parents('.cell-parent').find('#client_id').text();
		amount = parseFloat($('.final-price').text());
		service_id = $.urlParam('id');
		window.location = "addService.php?contract_id=" + contract_id + "&client_id=" + client_id + "&amount=" + amount + "&service=" + service_id;
	});

	$('.chosen-service').live("change", function() {
		if (this.checked) {
			var price = parseFloat($(this).parent().parent().find('.total').text());
			changeServicePrice(price, '+');
		} else {
			var price = parseFloat($(this).parent().parent().find('.total').text());
			changeServicePrice(price, '-');
		}

	});

	$('.discount').live("focusout", function() {
		var valu = 0;
		if ($.isNumeric($('.discount').val()))
			valu = $('.discount').val();

		var current = parseFloat($('.final-price').text());
		valu = current - ((valu / 100) * current);
		$('.final-price').text(valu + " ر.س");
	});

	$('.edit_type').live("click", function() {
		$(this).siblings('#type_text').hide();
		$(this).siblings('#edit_input').show();
	});

	$(".button").live("click", function() {
		$('.edit').show();
		$('.parag').hide();
	});

	//Checking all periods to delete
	$("#delcheck").on("change", function() {
		if ($(this).prop("checked")) {
			$("input#del").prop("checked", true);
		} else {
			$("input#del").prop("checked", false);
		}
	});

	$('.save-botton-2').live("click", function() {
		if ($(this).closest(".reciept").valid()) {
			$(this).attr("disabled", "disabled");
			$(this).addClass("disabled-style");

			var data = $(this).closest(".reciept").serialize();
			$.ajax({
				type : "POST",
				url : "service_vouchers.php",
				data : data,
				dataType : "html",
				success : function(response) {
					contract_id = $('.contract_id').val();
					$.magnificPopup.close();
					$.magnificPopup.open({
						items : {
							src : 'edit-pop-ups/contract.php?id=' + contract_id
						},
						type : 'ajax',
						callbacks : {
							ajaxContentAdded : function() {
								if (response == 12) {
									checkCredit();
								}
							}
						}
					});

				}
			});
		} else {
		}
	});
	
	$('.save-botton-3').live("click", function() {
		if ($(this).closest(".reciept").valid()) {
			$(this).attr("disabled", "disabled");
			$(this).addClass("disabled-style");

			var data = $(this).closest(".reciept").serialize();
			$.ajax({
				type : "POST",
				url : "recipt_vouchers.php",
				data : data,
				dataType : "html",
				success : function(response) {
					contract_id = $('.contract_id').val();
					$.magnificPopup.close();
					$.magnificPopup.open({
						items : {
							src : 'edit-pop-ups/contract.php?id=' + contract_id
						},
						type : 'ajax',
						callbacks : {
							ajaxContentAdded : function() {
								if (response == 12) {
									checkCredit();
								}
							}
						}
					});

				}
			});
		} else {
		}
	});

	$('.print_reciet').live("click", function() {
		recipt_id = $(this).parent().siblings('td').find('select').val(); a
		if (recipt_id == null) {

		} else {
			$.magnificPopup.open({
				items : {
					src : 'view-pop-ups/reciept.php?id=' + recipt_id
				},
				type : 'ajax',
			});
		}
	});

	//Export Button click, Submits to exportExcel.php
	$('.export-button').live("click", function() {
		//save action
		var action = $(this).parents('form').attr("action");
		$(this).parents('form').attr("action", "exportExcel.php");
		$(this).parents('form').submit();
		$(this).parents('form').attr("action", action);

	});

	//Export PDF click, Submits to exportExcel.php
	$('.export-PDF').live("click", function() {
		//save action
		var action = $(this).parents('form').attr("action");
		$('#pdf_excel').val(1);
		$(this).parents('form').attr("action", "exportExcel.php");
		$(this).parents('form').submit();
		$(this).parents('form').attr("action", action);
		$('#pdf_excel').val(0);

	});

	$('.print_payment').live("click", function() {
		recipt_id = $(this).parent().siblings('td').find('select').val();
		if (recipt_id == null) {

		} else {
			$.magnificPopup.open({
				items : {
					src : 'view-pop-ups/payment.php?id=' + recipt_id
				},
				type : 'ajax',
				callbacks : {
					close : function() {
					}
				}
			});
		}
	});

	$('.print_service').live("click", function() {
		recipt_id = $(this).parent().siblings('td').find('select').val();
		if (recipt_id == null) {

		} else {
			$.magnificPopup.open({
				items : {
					src : 'view-pop-ups/service.php?id=' + recipt_id
				},
				type : 'ajax',
				callbacks : {
					close : function() {
					}
				}
			});
		}
	});

	$('.save-botton-4').live("click", function() {
		if ($(this).parents(".reciept-1").valid()) {
			var data = $(this).parents(".reciept-1").serialize();
			var error = 0;
			//check if insurance set is greater than the required insurance

			if (error == 0) {
				$(this).attr("disabled", "disabled");
				$(this).addClass("disabled-style");

				$.ajax({
					type : "POST",
					url : "payment_vouchers.php",
					data : data,
					dataType : "html",
					success : function(response) {
						contract_id = $('.contract_id').val();
						$.magnificPopup.close();
						$.magnificPopup.open({
							items : {
								src : 'edit-pop-ups/contract.php?id=' + contract_id
							},
							type : 'ajax',
							callbacks : {
								ajaxContentAdded : function() {
									if (response == 12) {
										checkCredit();
									}
								}
							}

						});
					}
				});
			}

		} else {
		}

	});

	$('.payment_type').live("change", function() {
		apart_name = $('.apartment_name').val();
		if ($('.payment_type').val() == 0) {
			$('.reason-1').val("بدل إيجار وحدة رقم " + apart_name);
			$('.reason').val("قيمة إيجار الوحدة رقم " + apart_name);
		} else {
			$('.reason').val("قيمة التأمين على الوحدة رقم " + apart_name);
			$('.reason-1').val("بدل تأمين على الوحدة رقم " + apart_name);
		}
	});

	function saveDetailsOnAjax() {
		data = $('#editContract').serialize();
		$.ajax({
			type : "POST",
			url : "editContract.php",
			data : data,
			dataType : "html"
		});

	}


	$('.check-out').live("click", function() {
		currentDate = new Date();

		if ($('#to-miladi').datepicker('getDate') > currentDate) {
			var didConfirm = confirm("هل تود عمل خروج للعقد قبل إنتهاء المدة؟ إذا كنت ترغب فى عمل الخروج بتاريخ اليوم اضغط موافق، وإذا كنت ترغب فى عمل الخروج بتاريخ العقد اضغط إلغاء");
			if (didConfirm == true) {
				//get start Date
				start = $('#from-miladi').datepicker('getDate');
				//set end date
				var days = Math.floor((currentDate - start) / 1000 / 60 / 60 / 24);
				$('#to-miladi').datepicker('setDate', currentDate);
				//change days
				$('.period-days').val(days);
				//change months
				$('.period-months').val(Math.floor(days / 30));
				//change end hijri date
				$('.show-from-hijri-to').text(writeIslamicDate(currentDate, 1));
				$('#show-from-hijri-to').val(writeIslamicDate(currentDate, 1));
				
				//change price according to new settings
				changePrice();
				max_discount = parseFloat($('#maxd').val());
				given_discount = parseFloat($('.get-discount').val());
				if (given_discount > max_discount) {
					alert("الخصم الذى أدخلته تجاوز القيمة المعطاه لأقصى خصم متاح، سيتم تغييره ليناسب الفترة المختارة");
					$('.get-discount').val(max_discount);
				}
				//changeRecentcontractId
				contract_id = $('.contract_id').val();
				$('.sendRecentContrat').val(contract_id);
				//send request
				$('.check-out').parents('form').submit();
				return;
			}
		}
		checkCredit();

	});

	$('.search-client').live("click", function(e) {
		data = $(this).parents('form').serialize();
		$.ajax({
			type : "GET",
			url : "choose-pop-ups/choose_client.php",
			dataType : "json",
			data : data,
			success : function(response) {
				$('.append-customer .cell-parent').remove();
				$.each(response, function(index, element) {
					$('.append-customer tbody').append('<tr class="cell-parent">');
					$('.append-customer tbody').append(' <td id="client-name">' + element.name + '</td>' + '<td >' + element.identification_number + '</td>' + '<td >' + element.mobile + '</td>' + '<td >' + element.Notes + '</td>' + '<td ><a href="#" style="color:#000" class="chosen-client blue" id="' + element.id + '">أختر</a></td>');
					$('.append-customer  tbody').append('</tr>');
				});
			}
		});
	});

	//Validate date ranges
	$("div#ap-edit").on("click", function(e) {
		var field;
		var error = 0;
		var seen = {};
		var status = new Boolean();
		$("[id^=from-]").each(function() {
			field = $(this);
			var idp = field.attr('id').split('-');
			var p1 = idp[1];
			var tid = "to-" + idp[1];
			var cid = "input#to-" + idp[1];
			seen[tid] = [];
			var cdate = new Date(field.attr('value'));
			var ctdate = new Date($(cid).attr('value'));
			//making sure that the current field has a valid date and not empty
			if (field.attr('value') != "" && field.attr('value') != "0000-00-00" && $(cid).attr('value') != "" && $(cid).attr('value') != "0000-00-00") {
				//current field id
				var p2 = 1;
				//loop through fields
				$("[id^=to-]").each(function() {
					//Get the id of the fields
					var id = $(this).attr('id');

					//check if the alert already displayed
					status = true;
					if (seen[id]) {
						if (seen[id].indexOf(tid) != -1) {
							status = false;
						}
					}
					//few checks to make sure that the values are filled with a date and not empty
					if (id != tid && $(this).attr('value') != "0000-00-00" && $(this).attr('value') != "" && $("input#from-" + p2).attr('value') != "" && $("input#from-" + p2).attr('value') != "0000-00-00" && status == true) {
						var tdate = new Date($(this).attr('value'));
						var date = new Date($("input#from-" + p2).attr('value'));
						//make sure that the period is after or before all the other periods
						if (!(((cdate > tdate) && (ctdate > tdate)) || ((cdate < date) && (ctdate < date)))) {
							alert("هناك تداخل بين الفترات " + p1 + " و " + p2);
							error = 1;
						}
					}
					//filling what we already checked against
					seen[tid].push(id);
					p2++;
				});
			}
		});
		if (error == 0) {
			field.parents('form').submit();
		}
	});

	/* $('.manual-ajax-pop').click(function(e){
	e.preventDefault();
	$('body').prepend('<div id="manual-ajax-pop"><input type="text" /></div>');
	});*/
	//discount value company
	$('input[name=discount]').on({
		change : function() {
			if (!$.isNumeric(($(this).attr("value")))) {
				$(this).attr("value", 0);
				alert("نسبة الخصم غير صحيحة");
			}
		}
	});

	$('#s_botton').click(function() {
		$(this).parents('form').submit();
	});

});

